package com.ruoyi.bus.qiniu;


import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @Desc 七牛云存储
 * @Author caiyanshan
 * @Param {No such property: code for class: Script1}
 * @Return {}
 * @Throws {}
 **/
public class QiniuCloudUtil {

  private final static Logger logger = LoggerFactory.getLogger(QiniuCloudUtil.class);
  

  // 设置需要操作的账号的AK和SK
  private static String ACCESS_KEY = null;
  private static String SECRET_KEY = null;
  // 要上传的空间名
  private static String BUCKET_NAME = null;
  // 要显示的域名
  private static String DOMAIN = null;
  
  private static ISysConfigService sysConfigService;
  
  public static ISysConfigService getUpLoadConfig(){
    if(sysConfigService == null){
      sysConfigService = SpringUtils.getBean(ISysConfigService.class);
    }
    return sysConfigService;
  }
  
  private static void init() {
    
    ACCESS_KEY = getUpLoadConfig().selectConfigByKey("qiniu.accesskey");
    SECRET_KEY = getUpLoadConfig().selectConfigByKey("qiniu.secret");
    BUCKET_NAME = getUpLoadConfig().selectConfigByKey("qiniu.bucketname");
    DOMAIN = getUpLoadConfig().selectConfigByKey("qiniu.domain");
    
    auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    flag = true;
  }
  
  /**
   * @Description 可上传图片，可上传视频，会根据后缀随意切换, 也可定义后缀名称
   * @Author caiyanshan
   * @Date 2021/3/15 9:15
   * @Param [file]
   * @Return com.alibaba.fastjson.JSONObject
   */
  public static JSONObject commonUpload(MultipartFile file){
    JSONObject json = new JSONObject();
    try{
      String originalName = file.getOriginalFilename();
      originalName = originalName.substring(originalName.lastIndexOf("."));
      return upload(file.getInputStream(), "bus/commom/" + System.currentTimeMillis() + originalName);
    }catch(Exception e){
      logger.error("commonUpload upload is error, the error is : " + e);
    }
    json.put("code", 500);
    json.put("msg", "上传失败，请检查日志.");
    return new JSONObject();
  }

  // 密钥
  private static Auth auth = null;
  
  private static boolean flag = false;//是否加再过配置

  //上传
  public static JSONObject upload(InputStream inputStream, String key){
    if(!flag){
      init();
    }
    if(StringUtils.isEmpty(key)){
      key = "bus/commom/" + System.currentTimeMillis() + ".jpg";
    }
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region2());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    JSONObject json = new JSONObject();
    try {
      if(auth == null){
        json.put("code", 500);
        json.put("msg","未配置相关参数,请检查配置.");
        return json;
      }
      String upToken = auth.uploadToken(BUCKET_NAME);
      try {
        Response response = uploadManager.put(inputStream, key, upToken, null, null);
        JSONObject result = JSONObject.parseObject(response.bodyString());
        if (null == result.get("error")) {
          result.put("key", DOMAIN + result.getString("key"));
          result.put("hash", DOMAIN + result.getString("hash"));
        }
        return result;
      } catch (QiniuException ex) {
        Response r = ex.response;
        logger.error(r.toString());
        json.put("code", 500);
        json.put("msg", r.toString());
        return json;
      }
    } catch (Exception e) {

    }
    return null;
  }
}



